<template>
  <div class="exec-excel-container">


    <div class="form-wrapper">
      <a-form :model="formState">
        <a-form-item name="excelFile" :rules="[{ required: true, message: '请选择文件' }]">
          <a-upload v-model:fileList="fileList" :multiple="false" accept=".xlsx,.xls" :before-upload="beforeUpload"
            @change="handleChange">
            <a-button type="primary">
              <upload-outlined />
              选择文件
            </a-button>
          </a-upload>
        </a-form-item>

        <!-- 工作表数量显示 -->
        <a-form-item v-if="worksheetCount > 0">
          <div class="sheet-count">
            共检测到 <span class="highlight">{{ worksheetCount }}</span> 个工作表
          </div>
        </a-form-item>



        <!-- 工作表标签页 -->
        <a-form-item v-if="worksheetCount > 0">
          <div class="tabs-wrapper">
            <a-tabs :activeKey="activeTabIndex" type="card" @change="handleTabChange">
              <a-tab-pane v-for="(worksheet, index) in worksheets" :key="index"
                :tab="`${worksheet.name} (${worksheet.dataCount}条数据)`">       
                <div class="tab-content">
                  <!-- 工作表信息 -->
                  <div class="worksheet-info">
                    <div class="info-item">
                      <span class="info-label">表头行：</span>
                      <span class="info-value">第{{ worksheet.headerRow }}行</span>
                    </div>
                    <div class="info-item">
                      <span class="info-label">数据起始行：</span>
                      <span class="info-value">第{{ worksheet.dataStartRow }}行</span>
                    </div>
                    <div class="info-item">
                      <span class="info-label">数据行数：</span>
                      <span class="info-value">{{ worksheet.dataCount }}行</span>
                    </div>
                  </div>
                  <div class="table-container" v-if="worksheet.data && worksheet.data.length > 0">
                    <div class="table-wrapper">
                      <a-table 
                        :columns="worksheet.columns" 
                        :dataSource="worksheet.data" 
                        :pagination="false"
                        :scroll="{ x: 'max-content' }" 
                        size="small"
                        bordered />
                    </div>

                  </div>
                  <div v-else class="no-data">
                    <p>该工作表暂无数据</p>
                  </div>
                </div>
              </a-tab-pane>
            </a-tabs>
          </div>
        </a-form-item>

        <!-- 空状态提示 -->
        <a-form-item v-else-if="excelStore.currentFile">
          <div class="empty-state">
            <p>暂无工作表数据</p>
          </div>
        </a-form-item>




      </a-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, nextTick, watch } from 'vue';
import * as ExcelJS from 'exceljs';
import {
  UploadOutlined
} from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import type { UploadFile, TableColumnsType } from 'ant-design-vue';
import { useExcelStore } from '../store/excel';
import dayjs from 'dayjs';

// 定义组件事件
const emit = defineEmits(['upload-success', 'file-selected', 'file-processed', 'file-error']);

// 定义组件属性
const props = defineProps({
  // 是否只显示有数据的列，默认为true
  showOnlyDataColumns: {
    type: Boolean,
    default: true
  }
});

// 使用Excel store
const excelStore = useExcelStore();

// 日期格式化函数
const formatCellValue = (value: any): any => {
  if (value === null || value === undefined) {
    return '';
  }
  
  // 处理Date对象
  if (value instanceof Date) {
    return dayjs(value).format('YYYY-MM-DD');
  }
  
  // 处理ExcelJS的Date对象
  if (value && typeof value === 'object' && value.constructor && value.constructor.name === 'Date') {
    return dayjs(value).format('YYYY-MM-DD');
  }
  
  // 处理时间戳
  if (typeof value === 'number' && value > 1000000000000) {
    return dayjs(value).format('YYYY-MM-DD');
  }
  
  // 处理字符串格式的日期
  if (typeof value === 'string' && value.includes('GMT')) {
    try {
      const date = new Date(value);
      if (!isNaN(date.getTime())) {
        return dayjs(date).format('YYYY-MM-DD');
      }
    } catch (e) {
      // 如果解析失败，返回原值
    }
  }
  
  return value;
};

// 添加computed属性确保响应式更新
const worksheets = computed(() => {
  console.log('worksheets computed triggered:', excelStore.worksheets);
  return excelStore.worksheets;
});
const worksheetCount = computed(() => {
  console.log('worksheetCount computed triggered:', excelStore.worksheetCount);
  return excelStore.worksheetCount;
});
const activeTabIndex = computed(() => {
  console.log('activeTabIndex computed triggered:', excelStore.activeTabIndex);
  return excelStore.activeTabIndex;
});

console.log(excelStore,'excelStore');

// 监听worksheets变化
watch(() => excelStore.worksheets, (newWorksheets) => {
  console.log('Worksheets changed:', newWorksheets);
}, { deep: true });

// 简化的表单状态，仅用于表单绑定
const formState = reactive<{
  excelFile?: File | null;
}>({});

// 文件列表（仅用于UI展示）
const fileList = ref<UploadFile[]>([]);

// 加载状态
const loading = ref(false);

// 处理文件上传前的校验
const beforeUpload = (file: File) => {
  const isExcel = file.type === 'application/vnd.ms-excel' || file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  if (!isExcel) {
    message.error('请上传Excel文件！');
    return false;
  }
  excelStore.setCurrentFile(file);
  formState.excelFile = file; // 更新表单状态，避免验证提示
  
  // 触发文件选择回调事件
  emit('file-selected', file);
  
  // 文件上传完成后自动执行处理
  setTimeout(() => {
    handleFinish();
  }, 100);
  
  return false; // 阻止默认上传行为
};

// 处理文件变化
const handleChange = ({ fileList: newFileList }: any) => {
  fileList.value = newFileList;
};



// 定义预期的表名和格式规则（用于数据解析）
const EXPECTED_SHEETS = [
  { 
    name: '金融资产', 
    headerRow: 3, 
    dataStartRow: 4
  },
  { 
    name: '客户', 
    headerRow: 3, 
    dataStartRow: 4
  },
  { 
    name: '分案关系', 
    headerRow: 1, 
    dataStartRow: 2
  }
];



// 处理文件
const handleExcelFile = async (file: File): Promise<void> => {
  loading.value = true;
  
  try {
    // 创建文件读取器
    const reader = new FileReader();

    // 读取文件内容
    const buffer = await new Promise<ArrayBuffer>((resolve, reject) => {
      reader.onload = (e) => {
        if (e.target?.result instanceof ArrayBuffer) {
          resolve(e.target.result);
        } else {
          reject(new Error('无法读取文件内容'));
        }
      };
      reader.onerror = reject;
      reader.readAsArrayBuffer(file);
    });

    // 使用exceljs处理文件
    const workbook = new ExcelJS.Workbook();
    await workbook.xlsx.load(buffer);

    // 处理每个工作表
    const processedWorksheets: any[] = [];

    workbook.worksheets.forEach((worksheet, index) => {
      const expectedSheet = EXPECTED_SHEETS[index];
      
      // 解析表格数据
      const data: any[] = [];
      const headers: string[] = [];
      const tableColumns: TableColumnsType<any> = [];
      const headerRowNumber = expectedSheet.headerRow;
      const dataStartRowNumber = expectedSheet.dataStartRow;

      // 检查表头行是否存在
      const headerRow = worksheet.getRow(headerRowNumber);
      if (!headerRow || !headerRow.values || !Array.isArray(headerRow.values) || headerRow.values.length <= 1) {
        return;
      }

      // 解析表头
      for (let colNumber = 1; colNumber < (headerRow.values as any[]).length; colNumber++) {
        const cellValue = (headerRow.values as any[])[colNumber];
        const headerName = cellValue?.toString()?.trim() || `列${colNumber}`;
        headers[colNumber - 1] = headerName;
      }

      // 解析数据行
      let dataRowCount = 0;
      const allData: any[] = []; // 临时存储所有数据
      
      worksheet.eachRow({ includeEmpty: false }, (row, rowNumber) => {
        if (rowNumber >= dataStartRowNumber) {
          const rowData: any = { key: `row_${rowNumber}` };
          let hasData = false;
          
          for (let colNumber = 1; colNumber <= headers.length; colNumber++) {
            const cellValue = (row.values as any[])?.[colNumber];
            const colKey = `col${colNumber}`;
            // 格式化单元格值
            rowData[colKey] = formatCellValue(cellValue);
            
            // 检查是否有非空数据
            if (cellValue !== null && cellValue !== undefined && cellValue !== '') {
              hasData = true;
            }
          }
          
          // 只添加有数据的行
          if (hasData) {
            allData.push(rowData);
            dataRowCount++;
          }
        }
      });

      // 分析哪些列有数据
      const columnsWithData = new Set<number>();
      
      if (props.showOnlyDataColumns) {
        // 检查每一列是否有数据
        for (let colNumber = 1; colNumber <= headers.length; colNumber++) {
          const colKey = `col${colNumber}`;
          let hasColumnData = false;
          let nonEmptyCount = 0;
          
          // 检查所有行中这一列是否有数据
          for (const rowData of allData) {
            const cellValue = rowData[colKey];
            // 更严格的数据检查
            if (cellValue !== null && 
                cellValue !== undefined && 
                cellValue !== '' && 
                !(typeof cellValue === 'string' && cellValue.trim() === '') &&
                cellValue !== 0) {
              hasColumnData = true;
              nonEmptyCount++;
            }
          }
          
          // 只有当列中有至少一个非空数据时才显示该列
          if (hasColumnData && nonEmptyCount > 0) {
            columnsWithData.add(colNumber);
          }
        }
      } else {
        // 如果不需要过滤，则显示所有列
        for (let colNumber = 1; colNumber <= headers.length; colNumber++) {
          columnsWithData.add(colNumber);
        }
      }

      // 只保留有数据的列
      for (const colNumber of columnsWithData) {
        const headerName = headers[colNumber - 1];
        
        // 计算列宽度（基于表头名称长度）
        const headerLength = headerName.length;
        const minWidth = 80;
        const maxWidth = 200;
        const calculatedWidth = Math.max(minWidth, Math.min(maxWidth, headerLength * 12 + 20));
        
        tableColumns.push({
          title: headerName,
          dataIndex: `col${colNumber}`,
          key: `col${colNumber}`,
          width: calculatedWidth,
          ellipsis: true,
          align: 'center',
          customRender: ({ text }: { text: any }) => {
            // 如果已经是格式化后的字符串，直接返回
            if (typeof text === 'string' && text.includes('-') && text.includes(':')) {
              return text;
            }
            // 否则再次格式化
            return formatCellValue(text);
          }
        });
      }

      // 过滤数据，只保留有数据的列
      data.push(...allData.map(rowData => {
        const filteredRowData: any = { key: rowData.key };
        for (const colNumber of columnsWithData) {
          const colKey = `col${colNumber}`;
          filteredRowData[colKey] = rowData[colKey];
        }
        return filteredRowData;
      }));

      // 创建工作表对象
      const worksheetData = {
        name: worksheet.name,
        data,
        columns: tableColumns,
        originalHeaders: headers,
        headerRow: headerRowNumber,
        dataStartRow: dataStartRowNumber,
        dataCount: dataRowCount,
        expectedFormat: expectedSheet
      };

      // 调试信息
      console.log(`工作表 "${worksheet.name}" 解析结果:`, {
        列过滤启用: props.showOnlyDataColumns,
        原始列数: headers.length,
        有数据的列数: columnsWithData.size,
        过滤掉的列数: headers.length - columnsWithData.size,
        有数据的列索引: Array.from(columnsWithData),
        过滤掉的列: props.showOnlyDataColumns ? headers.filter((_, index) => !columnsWithData.has(index + 1)) : [],
        headers: headers,
        columns: tableColumns,
        dataCount: dataRowCount,
        sampleData: data.slice(0, 2) // 显示前两行数据作为示例
      });

      console.log(worksheetData,'data');

      // 添加工作表数据
      processedWorksheets.push(worksheetData);
    });

    // 保存到store
    excelStore.setWorksheets(processedWorksheets);

    console.log(processedWorksheets,'processedWorksheets');
    console.log(excelStore.worksheets,'excelStore.worksheets');
    
    // 强制触发响应式更新
    await nextTick();

    if (processedWorksheets.length > 0) {
      const totalDataCount = processedWorksheets.reduce((sum, sheet) => sum + sheet.dataCount, 0);
      const totalColumns = processedWorksheets.reduce((sum, sheet) => sum + sheet.columns.length, 0);
      const totalOriginalColumns = processedWorksheets.reduce((sum, sheet) => sum + sheet.originalHeaders.length, 0);
      
      if (props.showOnlyDataColumns) {
        const filteredColumns = totalOriginalColumns - totalColumns;
        message.success(`文件处理成功！共解析${processedWorksheets.length}个工作表，${totalDataCount}条数据，${totalColumns}个有效列（已过滤掉${filteredColumns}个空列）`);
      } else {
        message.success(`文件处理成功！共解析${processedWorksheets.length}个工作表，${totalDataCount}条数据，${totalColumns}个列`);
      }
    } else {
      message.warning('Excel文件中没有有效的工作表数据');
    }
  } catch (error) {
    console.error('处理Excel文件失败:', error);
    const errorMessage = error instanceof Error ? error.message : '处理Excel文件失败，请重试';
    message.error(errorMessage);
    throw error; // 重新抛出错误，让调用者处理
  } finally {
    loading.value = false;
  }
};

// 提交表单
const handleFinish = async () => {
  if (excelStore.currentFile) {
    try {
      await handleExcelFile(excelStore.currentFile);
      
      // 触发文件处理成功事件
      emit('file-processed', {
        fileName: excelStore.currentFile.name,
        fileType: excelStore.currentFile.type,
        fileUrl: '', // 这里可以根据需要设置文件URL
        caseId: '', // 这里可以根据需要设置案件ID
        worksheets: excelStore.worksheets,
        worksheetCount: excelStore.worksheetCount
      });
    } catch (error) {
      // 触发文件处理错误事件
      const errorMessage = error instanceof Error ? error.message : '文件处理失败';
      emit('file-error', errorMessage);
    }
  }
};



// 处理标签页切换
const handleTabChange = (key: string) => {
  excelStore.setActiveTabIndex(parseInt(key));
};


</script>

<style scoped>
.exec-excel-container {
  max-width: 100%;
  margin: 0 auto;
}

/* 标题样式 */
.component-title {
  font-size: 20px;
  font-weight: 600;
  color: #1a1a1a;
  margin-bottom: 16px;
}

/* 描述样式 */
.component-description {
  color: #666;
  margin-bottom: 24px;
  font-size: 14px;
}





/* 表单样式 */
.form-wrapper {
  margin-bottom: 24px;
}



/* 工作表数量提示 */
.sheet-count {
  font-size: 14px;
  color: #4096ff;
  font-weight: 500;
}

/* 标签页样式 */
.tabs-wrapper {
  /* margin-top: 24px; */
}

.tab-content {
  /* padding: 20px 0; */
}

/* 工作表信息样式 */
.worksheet-info {
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  padding: 16px;
  margin-bottom: 20px;
  display: flex;
  gap: 24px;
  flex-wrap: wrap;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.info-label {
  color: #666;
  font-size: 14px;
}

.info-value {
  color: #1a1a1a;
  font-weight: 500;
  font-size: 14px;
}

/* 表格样式 */
.table-container {
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  overflow: hidden;
  margin-top: 16px;
}

.table-wrapper {
  min-height: 400px;
}





/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 64px 24px;
  color: #999;
}

.no-data {
  text-align: center;
  padding: 40px 24px;
  color: #999;
  background-color: #fafafa;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  margin-top: 16px;
}

/* 加载状态样式 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .exec-excel-container {
    padding: 16px;
    border-radius: 8px;
  }



  .worksheet-info {
    flex-direction: column;
    gap: 12px;
  }



  .table-wrapper {
    overflow-x: auto;
  }



  .component-title {
    font-size: 18px;
  }
}

/* 动画效果 */
.fade-enter {
  opacity: 0;
  transform: translateY(-10px);
}

.fade-enter-active {
  opacity: 1;
  transform: translateY(0);
  transition: opacity 0.3s, transform 0.3s;
}

.fade-leave {
  opacity: 1;
}

.fade-leave-active {
  opacity: 0;
  transition: opacity 0.3s;
}

/* 高亮样式 */
.highlight {
  color: #4096ff;
  font-weight: 500;
}

/* 工具提示样式 */
.tooltip {
  position: relative;
  cursor: help;
}

.tooltip::after {
  content: attr(data-tooltip);
  position: absolute;
  bottom: 100%;
  left: 50%;
  transform: translateX(-50%);
  background-color: #333;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  white-space: nowrap;
  opacity: 0;
  visibility: hidden;
  transition: opacity 0.3s, visibility 0.3s;
  z-index: 1000;
}

.tooltip:hover::after {
  opacity: 1;
  visibility: visible;
}
</style>